const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置multer存储
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    const uploadDir = path.join(__dirname, '../../../frontend/public/images/products');
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function(req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'product-' + uniqueSuffix + ext);
  }
});

// 配置上传限制
const upload = multer({
  storage: storage,
  limits: { fileSize: 2 * 1024 * 1024 }, // 限制2MB
  fileFilter: function(req, file, cb) {
    // 只接受jpg和png
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
      cb(null, true);
    } else {
      cb(new Error('只支持JPG和PNG格式图片!'), false);
    }
  }
});

// 配置渠道图标存储
const channelIconStorage = multer.diskStorage({
  destination: function(req, file, cb) {
    const dir = path.join(__dirname, '../../public/uploads/channels');
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    cb(null, dir);
  },
  filename: function(req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'channel-' + uniqueSuffix + ext);
  }
});

// 配置小票二维码存储
const qrCodeStorage = multer.diskStorage({
  destination: function(req, file, cb) {
    const dir = path.join(__dirname, '../../public/uploads/qrcodes');
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
    cb(null, dir);
  },
  filename: function(req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'qrcode-' + uniqueSuffix + ext);
  }
});

// 配置渠道图标上传限制
const uploadChannelIcon = multer({
  storage: channelIconStorage,
  limits: { fileSize: 2 * 1024 * 1024 }, // 限制2MB
  fileFilter: function(req, file, cb) {
    // 只接受jpg和png
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
      cb(null, true);
    } else {
      cb(new Error('只支持JPG和PNG格式图片!'), false);
    }
  }
});

// 配置小票二维码上传限制
const uploadQrCode = multer({
  storage: qrCodeStorage,
  limits: { fileSize: 2 * 1024 * 1024 }, // 限制2MB
  fileFilter: function(req, file, cb) {
    // 只接受jpg和png
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
      cb(null, true);
    } else {
      cb(new Error('只支持JPG和PNG格式图片!'), false);
    }
  }
});

// 导入控制器
const authController = require('../controllers/authController');
const userController = require('../controllers/userController');
const productController = require('../controllers/productController');
const categoryController = require('../controllers/categoryController');
const orderController = require('../controllers/orderController');
const channelController = require('../controllers/channelController');
const dashboardController = require('../controllers/dashboardController');
const departmentController = require('../controllers/departmentController');
const inventoryRoutes = require('./inventory');
const uploadController = require('../controllers/uploadController');

// 导入价格工具路由
const priceToolsRoutes = require('./admin/priceTools');

// 中间件
const { authMiddleware } = require('../middleware/auth');

// 导入系统设置路由
const systemSettingsRoutes = require('./systemSettings');

// 添加交班管理路由模块
const shiftsRoutes = require('./shifts');

// 导入系统路由
const systemRoutes = require('./system');

// 导入报表路由模块
const reportsRoutes = require('./reports');

// 导入真实支付路由
const realPaymentRoutes = require('./realPayments');

// 身份验证路由
router.post('/auth/login', authController.login);
router.post('/auth/refresh-token', authController.refreshToken);
router.post('/auth/logout', authMiddleware, authController.logout);

// 用户路由
router.get('/users', authMiddleware, userController.getAllUsers);
router.get('/users/:id', authMiddleware, userController.getUserById);
router.post('/users', authMiddleware, userController.createUser);
router.put('/users/:id', authMiddleware, userController.updateUser);
router.delete('/users/:id', authMiddleware, userController.deleteUser);

// 部门路由
router.get('/departments', authMiddleware, departmentController.getAllDepartments);
router.get('/departments/:id', authMiddleware, departmentController.getDepartmentById);
router.post('/departments', authMiddleware, departmentController.createDepartment);
router.put('/departments/:id', authMiddleware, departmentController.updateDepartment);
router.delete('/departments/:id', authMiddleware, departmentController.deleteDepartment);

// 商品路由
router.get('/products', productController.getAllProducts);
router.get('/products/:id', productController.getProductById);
router.post('/products', authMiddleware, productController.createProduct);
router.put('/products/:id', authMiddleware, productController.updateProduct);
router.delete('/products/:id', productController.deleteProduct);

// 分类路由
router.get('/categories', categoryController.getAllCategories);
router.get('/categories/:id', categoryController.getCategoryById);
router.post('/categories', authMiddleware, categoryController.createCategory);
router.put('/categories/:id', authMiddleware, categoryController.updateCategory);
router.delete('/categories/:id', authMiddleware, categoryController.deleteCategory);

// 订单路由
router.get('/orders', authMiddleware, orderController.getAllOrders);
router.get('/orders/:id', authMiddleware, orderController.getOrderById);
router.post('/orders', orderController.createOrder);
router.put('/orders/:id', authMiddleware, orderController.updateOrder);
router.delete('/orders/:id', authMiddleware, orderController.deleteOrder);

// 渠道路由
router.get('/channels', channelController.getAllChannels);
router.get('/channels/:id', channelController.getChannelById);
router.post('/channels', authMiddleware, channelController.createChannel);
router.put('/channels/:id', authMiddleware, channelController.updateChannel);
router.delete('/channels/:id', authMiddleware, channelController.deleteChannel);

// 渠道价格路由
router.get('/channels/:channelId/prices', channelController.getChannelPrices);
router.post('/channels/:channelId/prices', channelController.setChannelPrice);
router.post('/channels/:channelId/batch-prices', channelController.batchSetChannelPrices);

// 渠道价格对比路由
router.get('/channel-price-comparison', channelController.getChannelPriceComparison);

// 商品渠道价格路由
router.get('/product-channel-prices', async (req, res) => {
  try {
    console.log('请求商品渠道价格API');
    
    // 查询所有渠道价格
    const { PrismaClient } = require('@prisma/client');
    const prisma = new PrismaClient();
    
    const prices = await prisma.productPrice.findMany({
      select: {
        productId: true,
        channelId: true,
        price: true,
        discount: true
      }
    });
    
    console.log(`从数据库获取到 ${prices.length} 条价格记录`);
    
    // 检查是否有重复记录
    const uniqueKeys = new Set();
    const uniquePrices = [];
    
    for (const price of prices) {
      const key = `${price.productId}-${price.channelId}`;
      if (!uniqueKeys.has(key)) {
        uniqueKeys.add(key);
        uniquePrices.push(price);
      } else {
        console.warn(`发现重复的价格记录: 商品ID=${price.productId}, 渠道ID=${price.channelId}`);
      }
    }
    
    if (prices.length !== uniquePrices.length) {
      console.log(`检测到 ${prices.length - uniquePrices.length} 条重复记录，已去重`);
    }
    
    res.json({
      status: 'success',
      data: uniquePrices
    });
  } catch (error) {
    console.error('获取商品渠道价格失败:', error);
    res.status(500).json({
      status: 'error',
      message: '获取商品渠道价格失败',
      error: error.message
    });
  }
});

// 库存管理路由 - 临时禁用
// router.use('/inventory', inventoryRoutes);

// 入库单路由
const stockInRoutes = require('./stockIn');
router.use('/inventory/stock-in', stockInRoutes);

// 出库单路由
const stockOutRoutes = require('./stockOut');
router.use('/inventory/stock-out', stockOutRoutes);

// 价格工具路由
router.use('/price-tools', priceToolsRoutes);

// 仪表盘数据路由
router.get('/dashboard/sales', authMiddleware, dashboardController.getSalesData);
router.get('/dashboard/orders', authMiddleware, dashboardController.getOrdersData);
router.get('/dashboard/products', authMiddleware, dashboardController.getProductsData);
router.get('/dashboard/channels', authMiddleware, dashboardController.getChannelData);

// 支付方式路由
router.get('/payment-methods', (req, res) => {
  // 返回支付方式配置
  const paymentMethods = [
    { id: 'cash', name: '现金支付', icon: 'money' },
    { id: 'wechat', name: '微信支付', icon: 'wechat' },
    { id: 'alipay', name: '支付宝支付', icon: 'alipay' },
    { id: 'complimentary', name: '招待', icon: 'gift' }
  ];
  
  res.json({
    status: 'success',
    data: paymentMethods
  });
});

// 图片上传路由
router.post('/upload', upload.single('file'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        status: 'error',
        message: '没有上传文件'
      });
    }
    
    // 构建文件URL
    const fileUrl = `/images/products/${req.file.filename}`;
    
    res.json({
      status: 'success',
      message: '文件上传成功',
      data: {
        url: fileUrl,
        filename: req.file.filename
      }
    });
  } catch (error) {
    console.error('文件上传失败:', error);
    res.status(500).json({
      status: 'error',
      message: '文件上传失败: ' + error.message
    });
  }
});

// 渠道图标上传路由
router.post('/upload/channel-icon', authMiddleware, uploadChannelIcon.single('file'), uploadController.uploadChannelIcon);

// 小票二维码上传路由
router.post('/upload/qr-code', authMiddleware, uploadQrCode.single('file'), uploadController.uploadQrCode);

// 报表数据路由
router.get('/reports/data', (req, res) => {
  const { type, startDate, endDate } = req.query;
  
  console.log('请求报表数据:', { type, startDate, endDate });
  
  // 临时模拟各种报表数据
  // 这里应该调用报表服务或控制器获取真实数据
  if (type === 'sales-overview') {
    // 销售概览模拟数据
    const dates = [];
    const sales = [];
    const orders = [];
    
    // 生成30天的日期和销售数据
    for (let i = 30; i >= 1; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      
      const formattedDate = `${date.getMonth() + 1}-${date.getDate()}`;
      dates.push(formattedDate);
      
      sales.push(Math.floor(Math.random() * 8000) + 2000);
      orders.push(Math.floor(Math.random() * 80) + 20);
    }
    
    // 生成分类销售数据
    const categories = ['啤酒', '饮料', '零食', '熟食', '生鲜', '烟酒'];
    const categorySales = categories.map(name => ({
      name,
      amount: Math.floor(Math.random() * 15000) + 5000,
      count: Math.floor(Math.random() * 150) + 50
    }));
    
    // 生成时段销售分布
    const hourlyDistribution = [];
    for (let hour = 8; hour <= 22; hour++) {
      hourlyDistribution.push({
        hour,
        sales: Math.floor(Math.random() * 2500) + 500,
        orders: Math.floor(Math.random() * 25) + 5
      });
    }
    
    // 生成热销商品
    const topProducts = [];
    for (let i = 1; i <= 10; i++) {
      const categoryIndex = Math.floor(Math.random() * categories.length);
      const amount = Math.floor(Math.random() * 4000) + 1000;
      topProducts.push({
        rank: i,
        name: `商品${i}`,
        category: categories[categoryIndex],
        quantity: Math.floor(Math.random() * 90) + 10,
        amount,
        ratio: ((amount / 50000) * 100).toFixed(2)
      });
    }
    
    res.json({
      status: 'success',
      data: {
        totalSales: 85629.75,
        totalOrders: 923,
        avgOrderValue: 92.77,
        totalItems: 3826,
        avgItemPrice: 22.38,
        salesGrowth: 12.5,
        orderGrowth: 8.3,
        avgOrderGrowth: 4.2,
        lastPeriodSales: 76113.56,
        lastPeriodOrders: 852,
        lastPeriodAvgOrder: 89.34,
        salesTrend: {
          dates,
          sales,
          orders
        },
        categorySales,
        hourlyDistribution,
        topProducts
      }
    });
  } else if (type === 'transaction-analysis') {
    // 交易分析模拟数据
    const dates = [];
    const counts = [];
    const amounts = [];
    
    // 生成日期数据
    for (let i = 30; i >= 1; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      
      const formattedDate = `${date.getMonth() + 1}-${date.getDate()}`;
      dates.push(formattedDate);
      
      counts.push(Math.floor(Math.random() * 80) + 20);
      amounts.push(Math.floor(Math.random() * 8000) + 2000);
    }
    
    res.json({
      status: 'success',
      data: {
        totalTransactions: 923,
        avgTransactionAmount: 92.77,
        maxTransactionAmount: 356.50,
        maxTransactionDate: '2023-05-15',
        dailyAvgTransactions: 30.77,
        peakDailyTransactions: 45,
        transactionGrowth: 8.3,
        avgTransactionGrowth: 4.2,
        lastPeriodTransactions: 852,
        lastPeriodAvgAmount: 89.34,
        transactionTrend: {
          day: {
            dates,
            counts,
            amounts
          },
          week: {
            dates: ['第1周', '第2周', '第3周', '第4周'],
            counts: [120, 145, 135, 150],
            amounts: [11500, 12800, 12000, 13500]
          },
          month: {
            dates: ['1月', '2月', '3月', '4月', '5月'],
            counts: [720, 680, 750, 800, 820],
            amounts: [65000, 62000, 68000, 72000, 75000]
          }
        },
        paymentMethodDistribution: [
          { method: '微信支付', amount: 45000, count: 500 },
          { method: '支付宝', amount: 30000, count: 350 },
          { method: '现金', amount: 10000, count: 100 },
          { method: '其他', amount: 5000, count: 50 }
        ],
        hourlyDistribution: Array.from({ length: 14 }, (_, i) => ({
          hour: i + 9,
          amount: Math.floor(Math.random() * 4000) + 1000,
          count: Math.floor(Math.random() * 40) + 10
        })),
        transactions: Array.from({ length: 100 }, (_, i) => ({
          id: `TX${String(i+1).padStart(6, '0')}`,
          time: `2023-05-${Math.floor(Math.random() * 30) + 1} ${String(Math.floor(Math.random() * 14) + 9).padStart(2, '0')}:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}`,
          amount: Math.floor(Math.random() * 300) + 20,
          items: Math.floor(Math.random() * 10) + 1,
          paymentMethod: ['微信支付', '支付宝', '现金'][Math.floor(Math.random() * 3)],
          memberId: Math.random() > 0.3 ? Math.floor(Math.random() * 1000) + 1 : null,
          memberName: Math.random() > 0.3 ? `会员${Math.floor(Math.random() * 1000) + 1}` : null,
          memberPhone: Math.random() > 0.3 ? `1${Math.floor(Math.random() * 10)}${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}` : null,
          cashier: `收银员${Math.floor(Math.random() * 5) + 1}`,
          couponAmount: Math.random() > 0.7 ? Math.floor(Math.random() * 20) + 5 : 0,
          items: Array.from({ length: Math.floor(Math.random() * 5) + 1 }, (_, j) => ({
            name: `商品${Math.floor(Math.random() * 100) + 1}`,
            price: Math.floor(Math.random() * 50) + 10,
            quantity: Math.floor(Math.random() * 5) + 1,
            subtotal: function() { return this.price * this.quantity; }()
          }))
        }))
      }
    });
  } else {
    // 其他报表类型
    res.json({
      status: 'success',
      data: {
        message: `报表类型 ${type} 的数据正在开发中`
      }
    });
  }
});

// 报表导出路由
router.get('/reports/export', (req, res) => {
  const { type, startDate, endDate, format } = req.query;
  
  // 这里应该实现真正的报表导出功能
  // 临时返回一个消息
  res.json({
    status: 'success',
    message: `${type}报表导出功能正在开发中，请稍后再试`
  });
});

// 注册系统设置路由
router.use('/system-settings', systemSettingsRoutes);

// 注册交班管理路由
router.use('/shifts', shiftsRoutes);

// 注册系统路由
router.use('/system', systemRoutes);

// 注册报表路由
router.use('/reports', reportsRoutes);

// 注册真实支付路由
router.use('/real-payments', realPaymentRoutes);

module.exports = router;